package _Pan3D.texture
{
	import _Pan3D.display3D.analysis.ObjAnalysis;
	import _Pan3D.load.LoadInfo;
	import _Pan3D.load.LoadManager;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display3D.Context3D;
	import flash.display3D.Context3DTextureFormat;
	import flash.display3D.textures.Texture;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	
	/**
	 * @author MSN:liuyan3757@163.com  QQ: 421537900
	 */
	public class TextureManager extends EventDispatcher
	{
		private var _textureDic:Object;
		private var _loadFunDic:Object;
		private var _context:Context3D;
		
		private static var instance:TextureManager;
		
		public function TextureManager()
		{
			_textureDic = new Object;
			_loadFunDic = new Object;
		}
		public static function getInstance():TextureManager{
			if(!instance){
				instance = new TextureManager;
			}
			return instance;
		}
		public function init(context:Context3D):void{
			this._context = context;
		}
		public function addTexture(url:String,fun:Function,info:Object):void{
			if(_textureDic.hasOwnProperty(url)){
				fun(_textureDic[url],info);
			}else{
				if(!_loadFunDic.hasOwnProperty(url)){
					_loadFunDic[url] = new Array;
					var loaderinfo:LoadInfo = new LoadInfo(url,LoadInfo.BITMAP,onTextureLoad,false,url);
					LoadManager.getInstance().addSingleLoad(loaderinfo);
				}
				_loadFunDic[url].push({"fun":fun,"info":info});
			}
		}
		private function onTextureLoad(bitmap:Bitmap,url:String):void{
			var bitmapdata:BitmapData = bitmap.bitmapData;
			if(!checkBitmap(bitmapdata)){
				this.dispatchEvent(new Event("sizeError"));
				return;
			}
			var texture:Texture = this._context.createTexture(bitmapdata.width, bitmapdata.height, Context3DTextureFormat.BGRA, true);
			texture.uploadFromBitmapData(bitmapdata);
			
			var ary:Array = _loadFunDic[url];
			for each(var obj:Object in ary){
				obj.fun(texture,obj.info)
			}
			delete _loadFunDic[url];
			_textureDic[url] = texture;
		}
		private function checkBitmap(bitmapdata:BitmapData):Boolean{
			var w:Boolean = Math.log(bitmapdata.width)/Math.log(2) is int;
			var h:Boolean = Math.log(bitmapdata.height)/Math.log(2) is int;
			if(w && h){
				return true;
			}else{
				return false;
			}
		}
	}
}